<template>
  <div class="aui-wrapper aui-page__login">
    <div class="aui-content__wrapper">
      <main class="aui-content">
        <div class="login-header">
          <h2 class="login-brand">{{ $t('brand.lg') }}</h2>
        </div>
        <div class="login-body">
          <el-tabs v-model="activeName">
            <el-tab-pane label="用户密码登录" name="user">
              <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()"
                status-icon>
                <el-form-item>
                  <el-select v-model="$i18n.locale" class="w-percent-100">
                    <el-option v-for="(val, key) in i18nMessages" :key="key" :label="val._lang" :value="key">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="username">
                  <el-input v-model="dataForm.username" :placeholder="$t('login.username')"
                    @blur="getValidateCodeLogin">
                    <span slot="prefix" class="el-input__icon">
                      <svg class="icon-svg" aria-hidden="true">
                        <use xlink:href="#icon-user"></use>
                      </svg>
                    </span>
                  </el-input>
                </el-form-item>
                <el-form-item prop="password">
                  <el-input v-model="dataForm.password" type="password" :placeholder="$t('login.password')"
                    show-password>
                    <span slot="prefix" class="el-input__icon">
                      <svg class="icon-svg" aria-hidden="true">
                        <use xlink:href="#icon-lock"></use>
                      </svg>
                    </span>
                  </el-input>
                </el-form-item>
                <el-form-item prop="captcha" v-if="isValidateCodeLogin">
                  <el-row :gutter="20">
                    <el-col :span="14">
                      <el-input v-model="dataForm.captcha" :placeholder="$t('login.captcha')">
                        <span slot="prefix" class="el-input__icon">
                          <svg class="icon-svg" aria-hidden="true">
                            <use xlink:href="#icon-safetycertificate"></use>
                          </svg>
                        </span>
                      </el-input>
                    </el-col>
                    <el-col :span="10" class="login-captcha">
                      <img :src="captchaPath" @click="getCaptcha()">
                    </el-col>
                  </el-row>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="dataFormSubmitHandle()" class="w-percent-100" :loading="loading">
                    {{ $t('login.title') }}
                  </el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="手机快速登录" name="sms">
              <el-form :model="mobileForm" :rules="mobileRule" ref="mobileForm"
                @keyup.enter.native="mobileFormSubmitHandle()" status-icon>
                <el-form-item>
                  <el-select v-model="$i18n.locale" class="w-percent-100">
                    <el-option v-for="(val, key) in i18nMessages" :key="key" :label="val._lang" :value="key">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="loginKey">
                  <el-input v-model="mobileForm.loginKey" :placeholder="$t('login.mobile')">
                    <i slot="prefix" class="el-input__icon el-icon-phone-outline"></i>
                  </el-input>
                </el-form-item>
                <el-form-item prop="validateCode">
                  <el-col :span="10">
                    <el-input v-model="mobileForm.validateCode" :placeholder="$t('login.validateCode')">
                      <span slot="prefix" class="el-input__icon">
                        <svg class="icon-svg" aria-hidden="true">
                          <use xlink:href="#icon-lock"></use>
                        </svg>
                      </span>
                    </el-input>
                  </el-col>
                  <el-col :span="7" :offset="7">
                    <el-button @click="getMobileCode()" :disabled="mobileFlag" class="w-percent-100" :loading="loading">
                      {{ mobileBtnTitle }}
                    </el-button>
                  </el-col>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="mobileFormSubmitHandle()" class="w-percent-100" :loading="loading">
                    {{ $t('login.title') }}
                  </el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="邮箱快速登录" name="email">
              <el-form :model="emailForm" :rules="emailRule" ref="emailForm"
                @keyup.enter.native="emailFormSubmitHandle()" status-icon>
                <el-form-item>
                  <el-select v-model="$i18n.locale" class="w-percent-100">
                    <el-option v-for="(val, key) in i18nMessages" :key="key" :label="val._lang" :value="key">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="loginKey">
                  <el-input v-model="emailForm.loginKey" :placeholder="$t('login.email')">
                    <i slot="prefix" class="el-input__icon el-icon-user"></i>
                  </el-input>
                </el-form-item>
                <el-form-item prop="validateCode">
                  <el-col :span="10">
                    <el-input v-model="emailForm.validateCode" :placeholder="$t('login.validateCode')">
                      <span slot="prefix" class="el-input__icon">
                        <svg class="icon-svg" aria-hidden="true">
                          <use xlink:href="#icon-lock"></use>
                        </svg>
                      </span>
                    </el-input>
                  </el-col>
                  <el-col :span="7" :offset="7">
                    <el-button @click="getEmailCode()" :disabled="emailFlag" class="w-percent-100" :loading="loading">
                      {{ emailBtnTitle }}
                    </el-button>
                  </el-col>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="emailFormSubmitHandle()" class="w-percent-100" :loading="loading">
                    {{ $t('login.title') }}
                  </el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-row :gutter="10">
              <el-col :span="12">
                <el-link :underline="false" @click="gotoRegisterView()">立即注册</el-link>
              </el-col>
              <el-col :span="12">
                <el-link :underline="false" @click="gotoResetPasswordView()">忘记密码</el-link>
              </el-col>
            </el-row>
          </el-tabs>
        </div>
        <div class="login-footer">
          <p>
            <a href="http://www.uniedp.cn/#/login" target="_blank">{{ $t('login.demo') }}</a>
          </p>
          <p><a href="http://www.uniedp.cn" target="_blank">{{ $t('login.copyright') }}</a>2019 © uniedp.cn</p>
        </div>
      </main>
    </div>
  </div>
</template>

<script>
import debounce from 'lodash/debounce'
import { messages } from '@/i18n'
import { getUUID } from '@/utils'
import URLUtil from '@/utils/url'
import aes from '@/utils/aes.js'

import {
  validateMobile,
  validateEmail
} from '@/utils/validate'
export default {
  data () {
    return {
      returnUrl: '',
      appId: '',
      activeName: 'user',
      count: 60,
      timer: null,
      mobileFlag: false,
      emailFlag: false,
      mobileBtnTitle: this.$t('login.checkCodeBtn'),
      emailBtnTitle: this.$t('login.checkCodeBtn'),
      loading: false,
      i18nMessages: messages,
      captchaPath: '',
      dataForm: {
        username: '',
        password: '',
        uuid: '',
        captcha: ''
      },
      mobileForm: {
        loginType: 'mobile'
      },
      emailForm: {
        loginType: 'email'
      },
      isValidateCodeLogin: false
    }
  },
  computed: {
    dataRule () {
      return {
        username: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        password: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        captcha: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    },
    mobileRule () {
      return {
        loginKey: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' },
          { required: true, validator: validateMobile, trigger: 'blur' }
        ],
        validateCode: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    },
    emailRule () {
      return {
        loginKey: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' },
          { required: true, validator: validateEmail, trigger: 'blur' }
        ],
        validateCode: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    // 读取url?后参数
    let params = URLUtil.getURLParams()
    this.returnUrl = params.returnUrl
    this.appId = params.appId
    this.getValidateCodeLogin()
    this.getCaptcha()
  },
  methods: {
    gotoResetPasswordView () {
      this.$router.replace({ name: 'resetPassword' })
    },
    gotoRegisterView () {
      this.$router.replace({ name: 'register' })
    },
    // 获取验证码
    getCaptcha () {
      this.dataForm.captcha = ''
      this.dataForm.uuid = getUUID()
      this.captchaPath = `${window.SITE_CONFIG['apiURL']}/captcha?uuid=${this.dataForm.uuid}`
    },
    // 获取手机验证码
    getMobileCode () {
      this.$refs.mobileForm.validateField('loginKey', mobileError => {
        if (!mobileError) {
          const TIME_COUNT = 120
          // 发送手机验证码
          if (!this.timer) {
            this.count = TIME_COUNT
            this.mobileFlag = true
            // 验证手机号码是否正确
            this.getValidateCode(this.mobileForm.loginKey, this.mobileForm.loginType)
            this.mobileBtnTitle = '重新发送（' + this.count + '）'
            this.timer = setInterval(() => {
              if (this.count > 0 && this.count <= TIME_COUNT) {
                this.count--
                this.mobileBtnTitle = '重新发送（' + this.count + '）'
              } else {
                this.mobileFlag = false
                clearInterval(this.timer)
                this.timer = null
                this.mobileBtnTitle = '重新发送'
              }
            }, 1000)
          }
        } else {
          return false
        }
      })
    },
    // 获取邮箱验证码
    getEmailCode () {
      this.$refs.emailForm.validateField('loginKey', mobileError => {
        if (!mobileError) {
          const TIME_COUNT = 120
          // 发送手机验证码
          if (!this.timer) {
            this.count = TIME_COUNT
            this.emailFlag = true
            // 验证手机号码是否正确
            this.getValidateCode(this.emailForm.loginKey, this.emailForm.loginType)
            this.emailBtnTitle = '重新发送（' + this.count + '）'
            this.timer = setInterval(() => {
              if (this.count > 0 && this.count <= TIME_COUNT) {
                this.count--
                this.emailBtnTitle = '重新发送（' + this.count + '）'
              } else {
                this.emailFlag = false
                clearInterval(this.timer)
                this.timer = null
                this.emailBtnTitle = '重新发送'
              }
            }, 1000)
          }
        } else {
          return false
        }
      })
    },
    // 验证是否需要验证码
    getValidateCode (loginKey, type) {
      this.$http.get(`/getValidateCodeByLoginKey?loginKey=${loginKey}&type=${type}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return false
        }
      })
    },
    // 验证是否需要验证码
    getValidateCodeLogin () {
      this.$http.get(`/isValidateCodeLogin?username=${this.dataForm.username}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return
        }
        this.isValidateCodeLogin = res.data.isValidateCodeLogin
      }).catch(() => { })
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      var msg = this.$message
      this.loading = true
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          this.loading = false
          return false
        }
        let postData = {}
        postData = {
          ...postData,
          ...this.dataForm
        }
        if (this.$store.state.passwordEnc) {
          postData.password = aes.encrypt(postData.password, this.$store.state.passwordEncKey)
        }
        // console.log(aes.decrypt(postData.password, '123456'))
        this.$http.post('/login', postData).then(({ data: res }) => {
          if (res.code !== 0) {
            this.loading = false
            this.getCaptcha()
            this.getValidateCodeLogin()
            return false
          }
          console.log('login', this)
          if (this.returnUrl) {
            // 重定向
            let url = this.returnUrl
            url = URLUtil.urlConcat(url, 'token', res.data.token)
            location.href = url
          } else {
            this.$cookies.set('token', res.data.token)
            this.$router.replace({ name: 'home' })
          }
        }).catch((err) => {
          this.loading = false
          console.error(err)
          msg.error('系统异常，请联系管理员')
        })
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    // 手机验证码提交
    mobileFormSubmitHandle: debounce(function () {
      this.loading = true
      this.$refs.mobileForm.validate((valid) => {
        console.log(valid)
        if (!valid) {
          this.loading = false
          return false
        }
        this.postLoginValidateCode(this.mobileForm)
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    // 邮箱验证码提交
    emailFormSubmitHandle: debounce(function () {
      this.loading = true
      this.$refs.emailForm.validate((valid) => {
        if (!valid) {
          this.loading = false
          return false
        }
        this.postLoginValidateCode(this.emailForm)
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    postLoginValidateCode (formData) {
      this.$http.post('/loginByValidateCode', formData).then(({ data: res }) => {
        if (res.code !== 0) {
          this.loading = false
          return false
        }
        console.log('login', this)
        if (this.returnUrl) {
          // 重定向
          let url = this.returnUrl
          url = URLUtil.urlConcat(url, 'token', res.data.token)
          location.href = url
        } else {
          this.$cookies.set('token', res.data.token)
          this.$router.replace({ name: 'home' })
        }
      }).catch((err) => {
        this.loading = false
        console.error(err)
        this.$message.error('系统异常，请联系管理员')
      })
    }
  }
}
</script>
